/**
 * 
 */
package com.wistech.search.solr;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wistech.search.solr.dict.DictDetector;
import com.wistech.search.solr.dict.file.FileDictDetector;

/**
 * @author Liuye
 * 
 */
public class SolrDispatchFilterEx extends
		org.apache.solr.servlet.SolrDispatchFilter {
	private static final Logger log = LoggerFactory
			.getLogger(SolrDispatchFilterEx.class);
	public static final String PARAM_DICT_DIR = "dict.dir";
	public static final String PARAM_DICT_REFRESH_MODE = "dict.refresh.mode";
	public static final String PARAM_TERM_MIN_LENGTH = "term.min.length";
	public static final String PARAM_TERM_MAX_LENGTH = "term.max.length";
	private DictDetector detector;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.solr.servlet.SolrDispatchFilter#init(javax.servlet.FilterConfig
	 * )
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		super.init(config);

		// 启动词库侦测器
		log.info("启动词库侦测器.");
		startDetector(config);
	}

	private void startDetector(FilterConfig config) {
		// 获取词库目录
		String dictDir = config.getInitParameter(PARAM_DICT_DIR);
		DictDetector detector = new FileDictDetector(dictDir);
		// 获取词库刷新模式
		String refreshModeStr = config
				.getInitParameter(PARAM_DICT_REFRESH_MODE);
		if (refreshModeStr != null
				&& ("day".equalsIgnoreCase(refreshModeStr) || "hour"
						.equalsIgnoreCase(refreshModeStr))) {
			detector.setRefreshMode(DictDetector.RefreshMode
					.valueOf(refreshModeStr.toUpperCase()));
		}

		// 获取最小词条长度
		String minLengthStr = config.getInitParameter(PARAM_TERM_MIN_LENGTH);
		if (minLengthStr != null && minLengthStr.trim().length() > 0) {
			int minLength = Integer.parseInt(minLengthStr);
			detector.setMinLength(minLength);
		}
		// 获取最大词条长度
		String maxLengthStr = config.getInitParameter(PARAM_TERM_MAX_LENGTH);
		if (maxLengthStr != null && maxLengthStr.trim().length() > 0) {
			int maxLength = Integer.parseInt(maxLengthStr);
			detector.setMaxLength(maxLength);
		}
		detector.start();
		detector.loadDict();
		this.detector = detector;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.solr.servlet.SolrDispatchFilter#destroy()
	 */
	@Override
	public void destroy() {
		if (detector == null) {
			return;
		}
		log.info("停止词库侦测器.");
		detector.stop();
		detector = null;
		super.destroy();
	}

}
